package com.kerpow.KSheet.character;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;

import android.os.Environment;

public class Finder {
	
	public static final String SHEET_EXTENSION = ".dnd4e";
	
	private OnFileFoundHandler _fileFoundHandler;
	
	public interface OnFileFoundHandler{
		void OnFileFound(File f);
	}
	
	private FileFilter _filterDir = new FileFilter() {
		
		@Override
		public boolean accept(File pathname) {
			return pathname.isDirectory();
		}
	};
	
	private FileFilter _filterSheet = new FileFilter() {
		
		@Override
		public boolean accept(File pathname) {
			return pathname.isFile() && pathname.getName().indexOf(SHEET_EXTENSION) > -1;
		}
	};
	
	public void setOnFileFound(OnFileFoundHandler handler){
		_fileFoundHandler= handler;
	}
	
	
	public ArrayList<File> getSheets(){
		
		return getSheets(Environment.getExternalStorageDirectory());
	}
	
	private ArrayList<File> getSheets(File path){
		ArrayList<File> ret = new ArrayList<File>();
		try
		{
		//recurse all directories
		File[] dirs = path.listFiles(_filterDir);
		for(File dir : dirs)
			ret.addAll(getSheets(dir));
		
		//recurse all files in this dir
		File[] files = path.listFiles(_filterSheet);
		for(File file : files)
		{
			ret.add(file);
			if(_fileFoundHandler != null)  _fileFoundHandler.OnFileFound(file);
		}
		}catch(Exception ex){
			//Log.e("kerpow", "Finder.getSheets(): " + ex.getMessage());
		}
		return ret;
	}
}
